package com.xsq.dubbo.comsumer.filter;


import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.rpc.*;
import com.xsq.dubbo.comsumer.util.IPUtil;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @ClassName TransportIPFilter
 * @Description TODO
 * @Author xsq
 * @Date 2020/6/23 15:13
 **/
@Activate
public class TransportIPFilter implements Filter {


    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        System.out.println("过滤器生效啦");
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            String ipAddress = IPUtil.getIpAddress(requestAttributes.getRequest());
            RpcContext.getContext().setAttachment("ip", ipAddress);
        }
        try {
            return invoker.invoke(invocation);
        } finally {
            RpcContext.getContext().clearAttachments();
        }

    }
}
